package com.Txunda.fxw.ui.activity.other;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.Txunda.fxw.R;
import com.Txunda.fxw.base.utils.util.JSONUtils;
import com.Txunda.fxw.base.utils.util.L;
import com.Txunda.fxw.base.utils.util.ListUtils;
import com.Txunda.fxw.base.utils.util.MapUtils;
import com.Txunda.fxw.ui.base.BaseAty;
import com.Txunda.fxw.ui.fgt.WebAty;
import com.Txunda.fxw.ui.http.Company;
import com.Txunda.fxw.ui.adapter.model.SummaryModel;
import com.Txunda.fxw.ui.toolkit.util.DensityUtil;
import com.Txunda.fxw.ui.toolkit.util.PreferenceUtil;
import com.Txunda.fxw.ui.widget.XCSlideView;
import com.Txunda.fxw.view.RoundedImageView;
import com.bumptech.glide.Glide;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 详情
 *
 * @author Administrator
 */
public class SingleDetailAty extends BaseAty {

    private List<SummaryModel> list_data;
    @ViewInject(R.id.aty_title3_tv_center)
    private TextView aty_title3_tv_center;
    @ViewInject(R.id.aty_title3_tv_right2)
    private TextView aty_title3_tv_right2;
    @ViewInject(R.id.icon_logo)
    private RoundedImageView icon_logo;

    @ViewInject(R.id.company_list_lv)
    private PullToRefreshListView company_list_lv;

    private XCSlideView mSlideViewRight;
    private ListView area_lv;
    private MyAdapter adapter;
    private Bundle bundle;
    private String class_id;
    private String count = "1";

    private TextView tv_count; // 全部商圈总数
    private Company company;
    private int p = 1;
    /**
     * 地区id
     */
    private String district_id = "";
    /**
     * 省id
     */
    private String province_id = "";
    /**
     * 城市id
     */
    private String city_id = "";
    private String lat = "";
    private String lnt = "";
    private ArrayList<Map<String, String>> company_list_data;
    private CompanyAdapter companyAdapter;
    private ArrayList<SummaryModel> cityList;
    private ArrayList<SummaryModel> districtList;

    protected int index;
    private String districtName;
    private int dataType = 0;
    protected String cityName = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataType = getIntent().getIntExtra("dataType", 0);
        if (getIntent().getStringExtra("count") != null || !getIntent().getStringExtra("count").equals("null") || !getIntent().getStringExtra("count").equals("null")) {
            count = getIntent().getStringExtra("count");
        }
        aty_title3_tv_center.setText(getIntent().getStringExtra("title"));
        aty_title3_tv_right2.setVisibility(View.VISIBLE);
        icon_logo.setVisibility(View.VISIBLE);

        // 获取经度纬度
        lat = PreferenceUtil.readString(getApplicationContext(), PreferenceUtil.sp_lat);
        lnt = PreferenceUtil.readString(getApplicationContext(), PreferenceUtil.sp_lnt);
        showProgressDialog();
        getCompanyList();
        company_list_lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                p = 1;
                if (0 != dataType)
                    getCompanyList();
                else
                    getCompanyList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                p++;
                if (0 != dataType)
                    getCompanyList();
                else
                    getCompanyList();
            }
        });
        company_list_lv.onRefreshComplete();
        company_list_lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, String> item = company_list_data.get(position - 1);
                L.e("=====item=====", item.toString());
                bundle = new Bundle();
                // 店铺详情
                String com_id = item.get("com_id");
                String class_id = item.get("class_id");
                String name = item.get("name");
                if (0 != dataType) {// 网页
                    bundle.putString("url", item.get("url"));
                    bundle.putString("type", type);
                    bundle.putString("class_id", class_id);
                    bundle.putString("com_id", com_id);
                    bundle.putString("com_id", com_id);
                    bundle.putString("count", count);
                    startActivity(WebAty.class, bundle);
                    return;
                }
                bundle.putString("com_id", com_id);
                bundle.putString("class_id", class_id);
                bundle.putString("name", name);
                bundle.putString("type", type);
                bundle.putString("district_name", districtName);
                startActivity(DetailAty.class, bundle);
            }
        });
    }


//     bundle.putString("id", "15");
//                bundle.putString("title", "");
//                bundle.putInt("dataType", 1);
//                bundle.putString("type", "st");


    /**
     * 获取商家列表
     */
    private void getCompanyList() {
        company.companyList(lat, lnt, p, class_id, district_id, city_id, province_id, this);
    }

    @Override
    @OnClick({R.id.icon_logo})
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.icon_logo: // logo
                if (!mSlideViewRight.isShow()) {
                    mSlideViewRight.show();
                }
                showProgressDialog();
                company.summary(class_id, this);
                break;

            default:
                break;
        }
    }

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        super.onComplete(requestUrl, jsonStr);
        getCompanyList(requestUrl, jsonStr);// 商家列表
        getSummary(requestUrl, jsonStr);// 省
        getSummaryCity(requestUrl, jsonStr);// 市
        getSummaryDistrict(requestUrl, jsonStr);// 地区
    }

    /**
     * 区
     */
    private void getSummaryDistrict(String requestUrl, String jsonStr) {
        if (requestUrl.contains("summaryDistrict")) { // 地区
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            if (MapUtils.isEmpty(map))
                return;
            if ("success".equals(map.get("flag"))) {
                districtList.clear();
                Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                if (MapUtils.isEmpty(data))
                    return;
                data.get("count");
                List<Map<String, String>> tempList = JSONUtils.parseKeyAndValueToMapList(data.get("list"));
                if (!ListUtils.isEmpty(tempList)) {
                    for (Map<String, String> temp : tempList) {
                        districtList
                                .add(new SummaryModel(temp.get("city_name"), temp.get("district_id"), temp.get("c_count")));
                    }
                    adapter = new MyAdapter(districtList);
                    area_lv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    area_lv.setOnItemClickListener(new OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // 地区id
                            districtName = districtList.get(position).getName();
                            showToast("已切换至" + districtName);
                            aty_title3_tv_right2.setText(cityName);
                            adapter.notifyDataSetChanged();

                            district_id = districtList.get(position).getId();
                            // 刷新商家列表数据
                            p = 1;
                            showProgressDialog();
                            getCompanyList();

                            if (mSlideViewRight.isShow()) {
                                mSlideViewRight.dismiss();
                            }
                        }
                    });
                }

            }
        }
    }

    /**
     * 市
     */
    private void getSummaryCity(String requestUrl, String jsonStr) {
        if (requestUrl.contains("summaryCity")) { // 市级
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            if ("success".equals(map.get("flag"))) {
                cityList.clear();
                Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                String count = data.get("count");
                tv_count.setText(count);
                for (Map<String, String> temp : JSONUtils.parseKeyAndValueToMapList(data.get("list"))) {
                    cityList.add(new SummaryModel(temp.get("city_name"), temp.get("city_id"), temp.get("c_count")));
                }
                adapter = new MyAdapter(cityList);
                area_lv.setAdapter(adapter);
                // 获取商家列表

                area_lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        // 回传district_id
                        city_id = cityList.get(position).getId(); // id
                        // 获取区县列表
                        showProgressDialog();
                        company.summaryDistrict(class_id, city_id, SingleDetailAty.this);

                        index = position;
                        adapter.notifyDataSetChanged();
                        // 保存本地数据
                        cityName = cityList.get(position).getName();
                        PreferenceUtil.write(getApplicationContext(), PreferenceUtil.sp_mode, cityName);

                        aty_title3_tv_right2.setText(cityList.get(position).getName());
                        adapter.notifyDataSetChanged();

                        // showProgressDialog();
                        // p = 1;
                        // getCompanyList();
                        // if (mSlideViewRight.isShow()) {
                        // mSlideViewRight.dismiss();
                        // return;
                        // }
                    }
                });
            }
        }
    }

    /**
     * 省
     */
    private void getSummary(String requestUrl, String jsonStr) {
        if (requestUrl.contains("summary")) { // 省级地区
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            if ("success".equals(map.get("flag"))) {
                list_data.clear();
                final Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                String count = data.get("count"); // 全部商圈总数
                tv_count.setText(count);
                for (Map<String, String> temp : JSONUtils.parseKeyAndValueToMapList(data.get("list"))) {
                    list_data.add(
                            new SummaryModel(temp.get("province_name"), temp.get("province_id"), temp.get("c_count")));
                }

                adapter = new MyAdapter(list_data);
                area_lv.setAdapter(adapter);

                area_lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        province_id = list_data.get(position).getId(); // 地区id

                        showProgressDialog();
                        company.summaryCity(class_id, province_id, SingleDetailAty.this); // 省集合
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }
    }

    /**
     * 获取商家列表
     */
    private void getCompanyList(String requestUrl, String jsonStr) {
        if (requestUrl.contains("companyList")) { // 商家列表
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            if (MapUtils.isEmpty(map))
                return;
            if ("success".equals(map.get("flag"))) {
                if (p == 1) {
                    company_list_data.clear();
                    company_list_data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));
                    company_list_lv.setAdapter(companyAdapter);
                } else {
                    ArrayList<Map<String, String>> company_more_data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));
                    company_list_data.addAll(company_more_data);
                    companyAdapter.notifyDataSetChanged();
                }
                company_list_lv.onRefreshComplete();
            }
        }
    }

    @Override
    public void onError(String requestUrl, Map<String, String> error) {
        company_list_lv.onRefreshComplete();
        removeProgressDialog();
        removeProgressContent();
        try {
            districtName = cityList.get(index).getName();
            showToast("已切换至" + districtName);
            aty_title3_tv_right2.setText(districtName);
            adapter.notifyDataSetChanged();
            /*
             * 地区id
             */
            p = 1;
            showProgressDialog();
            getCompanyList();
            if (mSlideViewRight.isShow()) {
                mSlideViewRight.dismiss();
            }
        } catch (Exception e) {
            L.e(e.getMessage());
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.aty_single_detail_aty;
    }

    @Override
    protected void initialized() {
        type = getIntent().getStringExtra("type");
        class_id = getIntent().getStringExtra("id");// 分类id
        districtList = new ArrayList<>();
        cityList = new ArrayList<>();
        String logo = PreferenceUtil.readString(getApplicationContext(), PreferenceUtil.sp_logo);
        Glide.with(this).load(logo).into(icon_logo);
        companyAdapter = new CompanyAdapter();
        company_list_data = new ArrayList<>();
        company = new Company();

        list_data = new ArrayList<>();
        String area_name = PreferenceUtil.readString(getApplicationContext(), PreferenceUtil.sp_mode);
        aty_title3_tv_right2.setText(area_name);

        // 侧滑
        Context mContext = this;
        // 屏幕宽度
        int mScreenWidth = DensityUtil.getScreenWidthAndHeight(mContext)[0];
        mSlideViewRight = XCSlideView.create(SingleDetailAty.this, XCSlideView.Positon.RIGHT);
        View menuViewRight = LayoutInflater.from(mContext).inflate(R.layout.layout_area, null);
        mSlideViewRight.setMenuView(SingleDetailAty.this, menuViewRight);
        tv_count = menuViewRight.findViewById(R.id.tv_count);
        mSlideViewRight.setMenuWidth(mScreenWidth * 6 / 9);

        area_lv = menuViewRight.findViewById(R.id.area_list);
    }

    @Override
    protected void requestData() {
    }


    @Override
    public void onBackPressed() {
        if (mSlideViewRight.isShow()) {
            mSlideViewRight.dismiss();
            return;
        }
        super.onBackPressed();
    }

    /**
     * 商家列表adapter
     *
     * @author Administrator
     */
    public class CompanyAdapter extends BaseAdapter {

        MyViewHolder vh;

        @Override
        public int getCount() {
            int ret = 0;
            if (company_list_data != null) {
                ret = company_list_data.size();
            }
            return ret;
        }

        @Override
        public Object getItem(int position) {
            return company_list_data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(SingleDetailAty.this).inflate(R.layout.item_company_list, parent,
                        false);
                vh = new MyViewHolder();
                ViewUtils.inject(vh, convertView);
                convertView.setTag(vh);
            } else {
                vh = (MyViewHolder) convertView.getTag();
            }

            vh.item_company_distance.setVisibility(View.GONE);
            vh.item_company_address.setVisibility(View.GONE);
            Glide.with(SingleDetailAty.this).load(company_list_data.get(position).get("cover_pic")).into(vh.item_company_img);
            vh.item_company_title.setText(company_list_data.get(position).get("name"));
            if (0 == dataType) {
                vh.item_company_distance.setVisibility(View.VISIBLE);
                vh.item_company_distance.setText(company_list_data.get(position).get("distance"));
                vh.item_company_address.setText(company_list_data.get(position).get("address") + "/");
                vh.item_company_address.setVisibility(View.VISIBLE);
            }

            return convertView;
        }

        class MyViewHolder {
            @ViewInject(R.id.item_company_img)
            private ImageView item_company_img;
            @ViewInject(R.id.item_company_title)
            private TextView item_company_title;
            @ViewInject(R.id.item_company_distance)
            private TextView item_company_distance;
            @ViewInject(R.id.item_company_address)
            private TextView item_company_address;
        }

    }

    /**
     * 地区筛选adapter
     *
     * @author Administrator
     */
    public class MyAdapter extends BaseAdapter {
        List<SummaryModel> list;
        MyViewHolder vh;

        public MyAdapter(List<SummaryModel> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            int ret = 0;
            if (list != null) {
                ret = list.size();
            }
            return ret;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(SingleDetailAty.this).inflate(R.layout.item_area_lv, parent, false);
                vh = new MyViewHolder();
                ViewUtils.inject(vh, convertView);
                convertView.setTag(vh);
            } else {
                vh = (MyViewHolder) convertView.getTag();
            }
            vh.item_area_name.setText(list.get(position).getName()); // 地区名称
            vh.item_area_num.setText(list.get(position).getCount()); // 数量

            return convertView;
        }

        class MyViewHolder {
            @ViewInject(R.id.item_area_name)
            private TextView item_area_name;
            @ViewInject(R.id.item_area_num)
            private TextView item_area_num;
        }
    }
}
